package link.tengfei.servlet;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ling.tengfei.service.AdminLoginService;
import ling.tengfei.service.AdminLoginServiceImpl;
import link.tengfei.util.CookieUtil;
import link.tengfei.bean.AdminUser;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String select = request.getParameter("select");
		String code = request.getParameter("code");
		System.out.println(DrawImgServlet.randomNum());
		if (code != null && code.equals(DrawImgServlet.randomNum())) {
			if (select != null && select.equals("1")) {
				String username = request.getParameter("username");
				String password = request.getParameter("password");
				String user = request.getParameter("user");
				String remember = request.getParameter("remember");
				AdminUser adminUser = new AdminUser();
				AdminLoginService adminLoginService = new AdminLoginServiceImpl();
				adminUser = adminLoginService.findUserByUsrAndPwd(username, password);
				if (adminUser != null && adminUser.getJudge() == 0 && user != null && user.equals("admin")) {
					System.out.println("登录到超级管理员");
					System.out.println(remember);
					// 记住密码，记住一个礼拜
					if (remember != null && remember.equals("on")) {
						CookieUtil.addCookie("cookie_name_pass", 7 * 24 * 60 * 60, request, response,
								URLEncoder.encode(username, "utf-8"), URLEncoder.encode(password, "utf-8"));
					}
					request.getRequestDispatcher("/WEB-INF/admin/main.html").forward(request, response);
				} else if (adminUser != null && adminUser.getJudge() == 1 && user != null && user.equals("admin")) {
					System.out.println("登录到普通管理员");
					// 记住密码，记住一个礼拜
					if (remember != null && remember.equals("on")) {
						CookieUtil.addCookie("cookie_name_pass", 7 * 24 * 60 * 60, request, response,
								URLEncoder.encode(username, "utf-8"), URLEncoder.encode(password, "utf-8"));
					}
					request.getRequestDispatcher("/WEB-INF/admin/admin_poor.html").forward(request, response);
				} else if (adminUser == null) {
					response.getWriter().print(1);
				}
			} else if (select != null && select.equals("0")) {

			}
		} else {
			response.getWriter().print(2);
		}

//			System.out.println("action-->" + action + ",select-->" + select + ",username-->" + username + ",password-->"
//					+ password + ",code-->" + code + ",remember-->" + remember);
	}
}
